package com.developer.platform.domain.service.impl;

import static com.developer.platform.RedisConstant.AUTHORIZATION_KEY;

import cn.hutool.core.bean.BeanUtil;
import com.developer.platform.domain.Menu;
import com.developer.platform.domain.security.AuthorizationInfo;
import com.developer.platform.domain.service.IAuthorizationSource;
import com.developer.platform.domain.service.IMenuService;
import com.veeker.redis.utils.RedisUtil;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2020-11-09
 */
@Service
public class AuthorizationSource implements IAuthorizationSource {

    private final IMenuService menuService;

    public AuthorizationSource(IMenuService menuService) {
        this.menuService = menuService;
    }

    @Override
    public List<AuthorizationInfo> loadResourceDefine() {
        Object value = RedisUtil.get(AUTHORIZATION_KEY);
        List<AuthorizationInfo> authorizationInfos;
        if(Objects.nonNull(value)){
            authorizationInfos = (List<AuthorizationInfo>)value;
        }else {
            List<Menu> menus = menuService.loadResourceDefine();
            authorizationInfos = menus.stream().map(
                    menu -> {
                        AuthorizationInfo authorizationInfo = new AuthorizationInfo();
                        BeanUtil.copyProperties(menu, authorizationInfo);
                        return authorizationInfo;
                    }
            ).collect(Collectors.toList());
            RedisUtil.set(AUTHORIZATION_KEY, authorizationInfos);
        }
        return authorizationInfos;
    }

    @Override
    public List<String> excludePathPatterns() {
        return Arrays.asList("/login",
                "/register",
                "/login/info",
                "/swagger**/**",
                "/remove",
                "/webjars/**" ,
                "/v2/**" ,
                "/api/**" ,
                "/system/dict/overal",
                "/doc.html");
    }

    @Override
    public void initializationResourceDefine() {
        RedisUtil.delete(AUTHORIZATION_KEY);
    }

}
